import { Injectable, UnauthorizedException } from '@nestjs/common';
import * as svgCaptcha from 'svg-captcha';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';

@Injectable()
export class AuthService {
  private captchaOptions = {
    size: 3, // 验证码长度
    noise: 0, // 干扰线条的数量
    color: true, // 验证码的字符是否有颜色，默认为true
    background: '#fff', // 背景色，默认随机
    width: 100, // 验证码图片的宽度
    height: 35, // 验证码图片的高度
  }
  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
  ) {}

  generateCaptcha() {
    return svgCaptcha.create(this.captchaOptions);
  }
  verifyCaptcha(inputCaptcha: string, sessionCaptcha: string): boolean {
    // 验证用户输入的验证码是否正确
    const checkoutInput = inputCaptcha && typeof inputCaptcha === 'string';
    const checkCaptcha = sessionCaptcha && typeof sessionCaptcha === 'string';
    if (checkoutInput && checkCaptcha) {
      return inputCaptcha.toLowerCase() === sessionCaptcha.toLowerCase();
    } else {
      return false;
    }
  }

  async signIn(username, pass) {
    const user = await this.usersService.findOneByName(username);
    console.log("验证用户名密码是否和表里一致", username, pass, user)
    if (user?.password !== pass) {
      // throw new UnauthorizedException();
      return {
        code: 1000,
        data: {},
        message: '或密码错误'
      }
    } else {
      const payload = { username: user.username, sub: user.id };
      return {
        access_token: await this.jwtService.signAsync(payload, {
          expiresIn: '10y', // token 设置为10年防止token过期
        }),
        userId: user.id
      };
    }
  }
}
